package com.hczt.xhminiapp.appapi.config;

import com.alibaba.fastjson.JSON;
import com.hczt.xhminiapp.common.bean.RtnResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author 红创-马海强
 * @date 2019-03-11 17:35
 * @description 权限拦截器
 */
@Component
@Slf4j
public class AccessInterceptor implements HandlerInterceptor {
    /**
     * 进入controller方法之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //如果header里没有token，而且是拦截接口，则返回错误
        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)) {
            printJson(response);
            return false;
        }

        return true;
    }

    /**
     * 调用完controller之后，视图渲染之前
     */
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 整个完成之后，通常用于资源清理
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    private static void printJson(HttpServletResponse response) {
        RtnResult result = new RtnResult(-1,"token无效,请重新登陆",null);
        String content = JSON.toJSONString(result);
        printContent(response, content);
    }

    /**
     * 组装返回结果
     * @param response
     * @param content
     */
    private static void printContent(HttpServletResponse response, String content) {
        try {
            response.reset();
            response.setContentType("application/json");
            response.setHeader("Cache-Control", "no-store");
            response.setCharacterEncoding("UTF-8");
            PrintWriter pw = response.getWriter();
            pw.write(content);
            pw.flush();
        } catch (Exception e) {
            log.error("拦截器组装返回结果时发生错误。", e);
            e.printStackTrace();
        }
    }

}
